package com.leap.meeting.view;

import com.github.lgooddatepicker.components.DateTimePicker;
import com.leap.meeting.dao.BaseDAO;
import com.leap.meeting.dao.imple.RecordDAOimple;
import com.leap.meeting.dao.imple.RoomDAOimple;
import com.leap.meeting.dao.imple.UserDAOimple;
import com.leap.meeting.pojo.Record;
import com.leap.meeting.pojo.Room;
import com.leap.meeting.pojo.User;
import com.leap.meeting.util.DataUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

public class Main_User extends JFrame implements MouseListener {

    static private UserDAOimple userDAOimple = new UserDAOimple();
    static private RoomDAOimple roomDAOimple = new RoomDAOimple();
    static private RecordDAOimple recordDAOimple = new RecordDAOimple();
    static private BaseDAO baseDAO = new BaseDAO();
    static private User user;
    static private Room newRoom;

    //设置窗口主题样式
    static {
        String lookAndFeel = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
        try {
            UIManager.setLookAndFeel(lookAndFeel);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedLookAndFeelException e) {
            throw new RuntimeException(e);
        }
    }

    Font f1 = new Font("微软雅黑", Font.BOLD,30);
    Font f2 = new Font("微软雅黑", Font.PLAIN, 15);
    Font f3 = new Font("微软雅黑", Font.PLAIN, 18);
    Font f4 = new Font("微软雅黑", Font.PLAIN, 12);

    JTabbedPane pane = new JTabbedPane();
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();
    JPanel p4 = new JPanel();

    JTable table1;
    JTable table3;
    JTable table4;
    //p1组件
    JTextField text1 = new JTextField();
    JButton button1 = new JButton("查询");
    JButton button2 = new JButton("预约");
    JButton yes = new JButton("确定");
    JButton no = new JButton("取消");
    JTextField attendees = new JTextField();
    JTextField speaker = new JTextField();
    JTextField topic = new JTextField();
    JTextArea content = new JTextArea();
    JDialog reJDialog;
    DateTimePicker startPicker = new DateTimePicker();
    DateTimePicker endPicker = new DateTimePicker();
    JScrollPane scrollPane1 = new JScrollPane();
    String p1_sql = "SELECT rooms.id AS id,name,address,seat_num AS seatNum,rooms.status AS status from rooms";
    String p1_sql2 = "SELECT id,name,address,seat_num AS seatNum,status from rooms where name like ?";
    String p1_sql3 = "INSERT INTO reservations(user_id, room_id, status,num) VALUES(?,?,'审核中',?)";
    String p1_sql4 = "INSERT INTO record(start_time, end_time, room_name, address, attendees, speaker, topic, training_content,express,num) values(?,?,?,?,?,?,?,?,0,?)";
    private String[] p1_head={"Id","会议室名称","地点","座位数","状态"};
    //p2组件
    JTextField account = new JTextField();
    JTextField name = new JTextField();
    JTextField apartment = new JTextField();
    JTextField phone = new JTextField();
    JTextField email = new JTextField();
    JTextField password = new JTextField();
    JTextField duty = new JTextField();
    JButton save = new JButton("保存");
    JButton quit = new JButton("退出登录");
    //p3组件
    String p3_sql = "SELECT real_name AS realName,name,address,seat_num AS seatNum,reservations.status AS status from reservations,rooms,user where reservations.room_id = rooms.id AND reservations.user_id = user.id AND user.id = ?";
    String p3_sql2 = "SELECT real_name AS realName,name,address,seat_num AS seatNum,reservations.status AS status from reservations,rooms,user where reservations.room_id = rooms.id AND reservations.user_id = user.id AND user.id = ? AND rooms.name LIKE ?";
    String p3_sql3 = "DELETE FROM reservations where user_id = ? AND room_id = ? AND status = '审核中' AND num = ?";
    String p3_sql4 = "DELETE FROM record where speaker = ? AND num = ?";
    JTextField text3 = new JTextField();
    JButton p3_button1 = new JButton("查询");
    JButton p3_button2 = new JButton("取消预约");
    JScrollPane scrollPane3 = new JScrollPane();
    private String[] p3_head = {"预约人","会议室","地点","人数","审核状态"};
    //p4组件
    String p4_sql = "SELECT id,room_name AS name,address,attendees,speaker,topic,start_time,end_time,training_content from record where speaker = ? AND express = 1";
    JScrollPane scrollPane4 = new JScrollPane();
    private String[] p4_head ={"Id","会议室名称","地点","参会人数","主持人","会议主题","开始时间","结束时间","会议内容"};


    public Main_User(String acc) {

        InitJFrame();
        InitTable(acc);
        this.setVisible(true);
    }

    private void InitJFrame() {
        this.setTitle("会议管理系统");
        this.setSize(900, 550);
        this.setLocationRelativeTo(null);//设置窗口居中
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setAlwaysOnTop(true);
        this.setResizable(false);//设置不可以通过拖动边框随意改变窗口大小

        //p1面板中的组件
        JLabel label = new JLabel("会议室名称");

        text1.setBounds(400, 30, 200, 25);
        button1.setBounds(620, 30, 80, 25);
        button2.setBounds(720, 100, 150, 40);
        button1.addMouseListener(this);
        button2.addMouseListener(this);
        yes.addMouseListener(this);
        no.addMouseListener(this);
        label.setBounds(300, 30, 80, 25);
        text1.setFont(f2);
        button1.setFont(f2);
        button2.setFont(f2);
        label.setFont(f2);

        scrollPane1.setBounds(10, 60, 700, 400);

        p1.setLayout(null);
        p1.add(scrollPane1);
        p1.add(text1);
        p1.add(button1);
        p1.add(button2);
        p1.add(label);

        //p2面板中的组件
        JLabel p2_title = new JLabel("个人信息");
        JLabel account_label = new JLabel("账号");
        JLabel name_label = new JLabel("姓名");
        JLabel apartment_label = new JLabel("部门");
        JLabel phone_label = new JLabel("手机号");
        JLabel email_label = new JLabel("邮箱");
        JLabel password_label = new JLabel("密码");
        JLabel duty_label = new JLabel("职务");

        p2_title.setBounds(350, 10, 200, 50);
        account_label.setBounds(150,80,100,25);
        name_label.setBounds(150,130,100,25);
        apartment_label.setBounds(150,180,100,25);
        phone_label.setBounds(150,230,100,25);
        email_label.setBounds(150,280,100,25);
        password_label.setBounds(150,330,100,25);
        duty_label.setBounds(150,380,100,25);

        account.setBounds(220, 80, 200, 25);
        name.setBounds(220, 130, 200, 25);
        apartment.setBounds(220, 180, 200, 25);
        phone.setBounds(220, 230,200, 25);
        email.setBounds(220, 280, 200, 25);
        password.setBounds(220, 330,200, 25);
        duty.setBounds(220, 380, 200, 25);

        p2_title.setFont(f1);
        account_label.setFont(f3);
        name_label.setFont(f3);
        apartment_label.setFont(f3);
        phone_label.setFont(f3);
        email_label.setFont(f3);
        password_label.setFont(f3);
        duty_label.setFont(f3);

        account.setFont(f3);
        name.setFont(f3);
        apartment.setFont(f3);
        phone.setFont(f3);
        email.setFont(f3);
        password.setFont(f3);
        duty.setFont(f3);

        account.setEditable(false);
        name.setEditable(false);
        apartment.setEditable(false);
        phone.setEditable(false);
        email.setEditable(false);
        password.setEditable(false);
        duty.setEditable(false);

        JButton edit = new JButton("修改");

        edit.setBounds(600, 100, 150, 30);
        save.setBounds(600, 200, 150, 30);
        quit.setBounds(600, 280, 150, 30);
        edit.setFont(f3);
        save.setFont(f3);
        quit.setFont(f3);
        save.setEnabled(false);

        save.addMouseListener(this);
        quit.addMouseListener(this);

        p2.setLayout(null);
        p2.add(p2_title);
        p2.add(account_label);
        p2.add(name_label);
        p2.add(apartment_label);
        p2.add(phone_label);
        p2.add(email_label);
        p2.add(password_label);
        p2.add(duty_label);

        p2.add(account);
        p2.add(name);
        p2.add(apartment);
        p2.add(phone);
        p2.add(email);
        p2.add(password);
        p2.add(duty);

        p2.add(edit);
        p2.add(save);
        p2.add(quit);

        edit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                account.setEditable(true);
                name.setEditable(true);
                apartment.setEditable(true);
                phone.setEditable(true);
                email.setEditable(true);
                password.setEditable(true);
                duty.setEditable(true);
                edit.setEnabled(false);
                save.setEnabled(true);
            }
        });

        save.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                account.setEditable(false);
                name.setEditable(false);
                apartment.setEditable(false);
                phone.setEditable(false);
                email.setEditable(false);
                password.setEditable(false);
                duty.setEditable(false);
                edit.setEnabled(true);
                save.setEnabled(false);
            }
        });

        //p3面板中的组件
        JLabel p3_label = new JLabel("会议室名称");

        text3.setBounds(400, 30, 200, 25);
        p3_button1.setBounds(620, 30, 80, 25);
        p3_button1.addMouseListener(this);
        p3_button2.setBounds(720, 100, 150, 40);
        p3_button2.addMouseListener(this);
        p3_label.setBounds(300, 30, 80, 25);
        scrollPane3.setBounds(10, 60, 700, 400);

        text3.setFont(f2);
        p3_button1.setFont(f2);
        p3_button2.setFont(f2);
        p3_label.setFont(f2);

        p3.setLayout(null);
        p3.add(scrollPane3);
        p3.add(text3);
        p3.add(p3_button1);
        p3.add(p3_button1);
        p3.add(p3_label);

        p3.add(p3_button2);

        //p4面板中的组件
        JLabel p4_title =new JLabel("个人会议记录");
        p4_title.setBounds(300, 10, 200, 50);
        p4_title.setFont(f1);

        scrollPane4.setBounds(10, 60, 850, 400);

        p4.setLayout(null);
        p4.add(p4_title);
        p4.add(scrollPane4);

        pane.add("会议室信息",p1);
        pane.add("个人信息",p2);
        pane.add("我的预约",p3);
        pane.add("个人会议记录",p4);

        this.add(pane);

    }

    private void InitTable(String acc) {
        //p1组件
        ResultSet p1_resultSet;
        try {
            p1_resultSet = DataUtil.querySet(p1_sql, null);
            table1 = new JTable(DataUtil.getArrays(p1_resultSet),p1_head);
            table1.setFont(f4);
            table1.setRowHeight(20);
            scrollPane1.setViewportView(table1);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //p2组件
        user = userDAOimple.selectByAccount(acc);
        account.setText(user.getAccount());
        name.setText(user.getRealName());
        apartment.setText(user.getApartment());
        phone.setText(user.getPhone());
        email.setText(user.getEmail());
        password.setText(user.getPassword());
        duty.setText(user.getDuty());

        //p3组件
        ResultSet p3_resultSet;
        try {
            p3_resultSet = DataUtil.querySet(p3_sql, user.getId());
            table3 = new JTable(DataUtil.getArrays(p3_resultSet), p3_head);
            table3.setFont(f4);
            table3.setRowHeight(20);
            scrollPane3.setViewportView(table3);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        //p4组件
        ResultSet p4_resultSet;
        try {
            p4_resultSet = DataUtil.querySet(p4_sql, user.getRealName());
            table4 = new JTable(DataUtil.getArrays(p4_resultSet), p4_head);
            table4.setFont(f4);
            table4.setRowHeight(20);
            scrollPane4.setViewportView(table4);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void mouseClicked(MouseEvent event) {
        Object obj = event.getSource();
        if (obj == button1){
            p1_roomSearch();
        }else if (obj == button2){
            p1_reserve();
        }else if (obj == save){
            User newUser = new User();
            newUser.setId(user.getId());
            newUser.setAccount(account.getText());
            newUser.setRealName(name.getText());
            newUser.setApartment(apartment.getText());
            newUser.setPhone(phone.getText());
            newUser.setEmail(email.getText());
            newUser.setPassword(password.getText());
            newUser.setDuty(duty.getText());

            int i = userDAOimple.update(newUser);
            if (i > 0) {
                System.out.println("修改成功！====="+newUser);
            }

        }else if (obj == quit){
            new Login();
            this.dispose();
        }else if (obj == p3_button1){
            p3_roomSearch();
        }else if (obj == p3_button2){
            p3_cancelReserve();
        }else if (obj == yes){
            int flag = 0;
            if(isAllFilled()){
                if (Integer.parseInt(attendees.getText()) > newRoom.getSeatNum()){
                    //弹窗提示
                    System.out.println("所填人数超过会议室最大人数！");
                    return;
                }
                List<Record> records = recordDAOimple.selectByName(newRoom.getName());
                for (Record record : records) {
                    if (record.getExpress() != 2){
                        if (isOverlapTwoTime(
                                DataUtil.asDate(startPicker.getDateTimePermissive()),
                                DataUtil.asDate(endPicker.getDateTimePermissive()),
                                DataUtil.asDate(record.getStartTime()),
                                DataUtil.asDate(record.getEndTime())
                        )) {
                            flag=1;
                        }
                    }
                }
                if (flag == 0) {
                    int i = baseDAO.executeUpdate(p1_sql3, user.getId(),newRoom.getId(),records.size()+1);
                    int j = baseDAO.executeUpdate(p1_sql4,startPicker.getDateTimePermissive(),endPicker.getDateTimePermissive(),newRoom.getName(),newRoom.getAddress(),attendees.getText(),speaker.getText(),topic.getText(),content.getText(),records.size()+1);
                    if (i > 0 && j > 0){
                        System.out.println("预约成功");
                        this.InitTable(user.getAccount());
                    }
                }else {
                    popWin("预约失败！预约时间段重复！");
                    return;
                }
            }else{
                popWin("请填满会议预约信息！");
                return;
            }
            reJDialog.dispose();
        }else if (obj == no){
            reJDialog.dispose();
        }
    }


    private void p1_roomSearch() {
        String find = text1.getText();
        ResultSet resultSet=null;
        if ("".equals(find)){
            System.out.println("11111111111111111111111111111");
            //显示全部会议信息
            try {
                resultSet = DataUtil.querySet(p1_sql, null);
                table1 = new JTable(DataUtil.getArrays(resultSet),p1_head);
                table1.setFont(f4);
                table1.setRowHeight(20);
                scrollPane1.setViewportView(table1);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            System.out.println("显示全部====================");
        }else {
            //显示搜索结果
            try {
                resultSet = DataUtil.querySet(p1_sql2, "%"+find+"%");
                if (resultSet==null){
                    System.out.println("未找到");
                    return;
                }
                table1 = new JTable(DataUtil.getArrays(resultSet),p1_head);
                table1.setFont(f4);
                table1.setRowHeight(20);
                scrollPane1.setViewportView(table1);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void p1_reserve() {
        int selectedRow = table1.getSelectedRow();
        if (selectedRow<0){
            System.out.println("请选择预约的对象!");
            return;
        }
        Object roomId = table1.getValueAt(selectedRow, 0);
        newRoom = roomDAOimple.selectById((Integer) roomId);
        System.out.println(newRoom);
        if ("占有".equals(newRoom.getStatus())){
            System.out.println("该会议室已被占有！请选择其他会议室！");
            return;
        }
        recordJDialog(newRoom,user.getRealName());
    }

    private boolean isAllFilled(){
        if (!attendees.getText().isEmpty()){
            if(!speaker.getText().isEmpty()){
                if(!topic.getText().isEmpty()){
                    if(!content.getText().isEmpty()){
                        if(startPicker.getDateTimePermissive()!=null){
                            if(endPicker.getDateTimePermissive()!=null){
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    private void p3_roomSearch() {
        String find = text3.getText();
        ResultSet resultSet;
        if ("".equals(find)){
            //显示全部会议信息
            try {
                resultSet = DataUtil.querySet(p3_sql, user.getId());
                table3 = new JTable(DataUtil.getArrays(resultSet),p3_head);
                table3.setFont(f4);
                table3.setRowHeight(20);
                scrollPane3.setViewportView(table3);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            System.out.println("显示全部====================");
        }else {
            //显示搜索结果
            try {
                resultSet = DataUtil.querySet(p3_sql2, user.getId(),"%"+find+"%");
                if (resultSet==null){
                    System.out.println("未找到");
                    return;
                }
                table3 = new JTable(DataUtil.getArrays(resultSet),p3_head);
                table3.setFont(f4);
                table3.setRowHeight(20);
                scrollPane3.setViewportView(table3);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }

    private void p3_cancelReserve() {
        int selectedRow = table3.getSelectedRow();
        if (selectedRow<0){
            System.out.println("请选择取消预约的对象!");
            return;
        }
        Object roomName = table3.getValueAt(selectedRow, 1);
        int roomId = roomDAOimple.selectByName((String) roomName).getId();
        List<Record> records = recordDAOimple.selectByName((String) roomName);
        System.out.println("==="+selectedRow+"==="+roomName);
        int i = baseDAO.executeUpdate(p3_sql3, user.getId(),roomId,records.size());
        int j = baseDAO.executeUpdate(p3_sql4, user.getRealName(),records.size());
        if (i > 0 && j > 0){
            System.out.println("修改成功");
            this.InitTable(user.getAccount());
        }else {
            //弹窗提示
            popWin("该会议已审核 无法取消！");
        }
    }

    private void recordJDialog(Room room, String name){
        reJDialog = new JDialog();
        reJDialog.setTitle("会议记录");
        reJDialog.setSize(400, 600);
        reJDialog.setLocationRelativeTo(null);
        reJDialog.setLayout(null);
        reJDialog.setAlwaysOnTop(true);
        reJDialog.setResizable(false);

        JLabel roomNameLabel = new JLabel("会议室名称");
        JLabel addressLabel = new JLabel("地点");
        JLabel attendeesLabel = new JLabel("参会人数");
        JLabel speakerLabel = new JLabel("演讲人");
        JLabel topicLabel = new JLabel("会议主题");
        JLabel contentLabel = new JLabel("会议内容");
        JLabel startLabel = new JLabel("开始时间");
        JLabel endLabel = new JLabel("结束时间");
        JTextField roomName = new JTextField();
        JTextField address = new JTextField();

        roomName.setFont(f2);
        address.setFont(f2);
        attendees.setFont(f2);
        speaker.setFont(f2);
        topic.setFont(f2);
        content.setFont(f2);

        roomNameLabel.setFont(f2);
        addressLabel.setFont(f2);
        attendeesLabel.setFont(f2);
        speakerLabel.setFont(f2);
        topicLabel.setFont(f2);
        contentLabel.setFont(f2);
        startLabel.setFont(f2);
        endLabel.setFont(f2);

        yes.setFont(f2);
        no.setFont(f2);

        roomNameLabel.setBounds(30, 10, 100, 50);
        addressLabel.setBounds(50, 60, 100, 50);
        attendeesLabel.setBounds(30, 110, 100, 50);
        speakerLabel.setBounds(30, 160, 100, 50);
        topicLabel.setBounds(30, 210, 100, 50);
        startLabel.setBounds(30, 260, 100, 50);
        endLabel.setBounds(30, 310, 100, 50);
        contentLabel.setBounds(30, 360, 100, 50);

        roomName.setBounds(120, 20, 150, 30);
        address.setBounds(120, 70, 150, 30);
        attendees.setBounds(120, 120, 150, 30);
        speaker.setBounds(120, 170, 150, 30);
        topic.setBounds(120, 220, 150, 30);
        startPicker.setBounds(120, 270, 250, 25);
        endPicker.setBounds(120, 320, 250, 25);
        content.setBounds(120, 370, 200, 100);

        roomName.setText("");
        address.setText("");
        attendees.setText("");
        speaker.setText("");
        topic.setText("");
        content.setText("");
        startPicker.clear();
        endPicker.clear();

        roomName.setEditable(false);
        address.setEditable(false);
        roomName.setText(room.getName());
        address.setText(room.getAddress());
        attendees.setText(room.getSeatNum().toString());
        speaker.setText(name);

        yes.setBounds(30, 500, 100, 40);
        no.setBounds(220, 500, 100, 40);

        reJDialog.add(roomNameLabel);
        reJDialog.add(addressLabel);
        reJDialog.add(attendeesLabel);
        reJDialog.add(speakerLabel);
        reJDialog.add(topicLabel);
        reJDialog.add(contentLabel);
        reJDialog.add(startLabel);
        reJDialog.add(endLabel);

        reJDialog.add(roomName);
        reJDialog.add(address);
        reJDialog.add(attendees);
        reJDialog.add(speaker);
        reJDialog.add(topic);
        reJDialog.add(content);

        reJDialog.add(startPicker);
        reJDialog.add(endPicker);
        reJDialog.add(yes);
        reJDialog.add(no);

        reJDialog.setModal(true);
        reJDialog.setVisible(true);

    }

    private boolean isOverlapTwoTime(Date startOne, Date endOne, Date startTwo, Date endTwo){
        if(!startOne.after(endTwo) && !endOne.before(startTwo) ){
           return true;
        }
        return false;
    }

    private void popWin(String str){
        JDialog dialog = new JDialog();
        dialog.setSize(350, 200);
        dialog.setAlwaysOnTop(true);
        dialog.setLocationRelativeTo(null);
        dialog.setLayout(null);
        JLabel label = new JLabel(str);
        label.setFont(f3);
        label.setBounds(70, 50, 300, 40);
        dialog.getContentPane().add(label);
        dialog.setModal(true);
        dialog.setVisible(true);
    }


    @Override
    public void mousePressed(MouseEvent e) {

    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }
}
